
//
//  BookPreviewDetailViewController.m
//  TeacherPro
//
//  Created by DCQ on 2017/9/5.
//  Copyright © 2017年 ZNXZ. All rights reserved.
//

#import "BookPreviewDetailViewController.h"
#import "BookPreviewModel.h"
#import "BookPreviewDirectoryHeaderView.h"
#import "BookPreviewDirectoryCell.h"
#import "BookPreviewDetailTitleCell.h"
#import "BookPreviewDetailTypeCell.h"
#import "PreviewPictureBookAudioViewController.h"
#import "CartoonPreviewDirectoryPlayCell.h"
#import "CartoonProfilePreviewCell.h"
#import "ProUtils.h"
#import "HSDownloadManager.h"
#import "HWCircleView.h"
#import "BookcaseViewController.h"
#import "BookHomeworkViewController.h"
#import "AssistantsHomeworkViewController.h"

NSString * const BookPreviewDirectoryHeaderViewIdentifier = @"BookPreviewDirectoryHeaderViewIdentifier";
NSString * const BookPreviewDirectoryCellIdentifier = @"BookPreviewDirectoryCellIdentifier";
NSString * const BookPreviewDirectoryTwoCellIdentifier = @"BookPreviewDirectoryTwoCellIdentifier";

NSString * const BookPreviewDetailTitleCellIdentifier = @"BookPreviewDetailTitleCellIdentifier";
NSString * const BookPreviewDetailTypeCellIdentifier = @"BookPreviewDetailTypeCellIdentifier";


NSString * const CartoonPreviewDirectoryPlayCellIdentifier = @"CartoonPreviewDirectoryPlayCellIdentifier";
NSString * const CartoonProfilePreviewCellIdentifier = @"CartoonProfilePreviewCellIdentifier";


#define bottomViewHeight  FITSCALE(50)
#define kSureBgBtnTag  777676
@interface BookPreviewDetailViewController ()
@property(nonatomic, copy) NSString * bookId;
@property(nonatomic, copy) NSString * bookType;
@property(nonatomic, strong)BookPreviewModel *detailModel;
@property(nonatomic, assign)BOOL isExists;
@property(nonatomic,strong)    NSDictionary * unityIconDic;//字段对应的图片

@property (nonatomic, strong) NSMutableArray * playCartoonBookArray;//播放的数据
@property (nonatomic, strong) NSMutableArray * cartoonBookDownloadUrlArray;//音频下载地址
@property (nonatomic, strong) NSMutableArray * cartoonBookImgArray;//图片
@property(nonatomic, assign) NSInteger currentDownPage;//
@property(nonatomic, assign) NSInteger downIndex;
@property (nonatomic, strong) HWCircleView *circleView;
@property (nonatomic, strong) UIView *mongoliaView;
@property(nonatomic, assign) BOOL isFromHome;
@end

@implementation BookPreviewDetailViewController
- (instancetype)initWithBookId:(NSString *)bookId withBookType:(NSString *)bookType withExistsBookcase:(BOOL)isExists{
    self = [super init];
    if (self) {
        self.bookId = bookId;
        self.bookType = bookType;
        self.isExists = isExists;
    }
    return self;
}
- (instancetype)initWithFromHomeBookId:(NSString *)bookId  withBookType:(NSString *)bookType withExistsBookcase:(BOOL)isExists{
    self = [super init];
    if(self){
        self.bookId = bookId;
        self.bookType = bookType;
        self.isExists = isExists;
        self.isFromHome = YES;
    }
    return self;
}
- (NSString *)getDescriptionText{
    
    return @"暂无数据~";
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItemTitle:@"书本预览"];
    [self requestQueryBook];
    self.unityIconDic = [ProUtils getHomworkDetailUnitIconDic];
//    self.unityIconDic =  @{
//                           @"hbpy":@"homework_icon_hbpy_new",
//                           @"yyyd":@"homework_icon_yyyd_new",
//                           @"hbxt":@"homework_icon_hbxt_new",
//                           @"chxx":@"homework_icon_chxx_new",
//                           @"zxlx":@"homework_zxlx_icon_new",
//                           @"tkwly":@"homework_tkwly_icon_new",
//                           @"ldkw":@"homework_ldkw_icon_new",
//                           @"dctx":@"homework_dctx_icon_new",
//                           @"ywdd":@"homework_tkwly_icon_new",
//                           @"khlx":@"homework_dctx_icon_new"
//                           };
    
  
    [self.view addSubview:self.mongoliaView];
    [self.view addSubview:self.circleView];
    [self configCollectionView];
}

 
- (void)configCollectionView{
    
    self.collectionView.backgroundColor = [UIColor clearColor];
    
    self.view.backgroundColor = project_background_gray;
}
//蒙层
- (UIView *)mongoliaView{
    if (!_mongoliaView) {
        _mongoliaView = [[UIView alloc] initWithFrame:self.view.frame];
        _mongoliaView.alpha = 0.5;
        _mongoliaView.hidden = YES;
        _mongoliaView.backgroundColor = [UIColor blackColor];
    }
    return _mongoliaView;
}
- (HWCircleView *)circleView{
    if (!_circleView) {
        _circleView = [[HWCircleView alloc] initWithFrame:CGRectMake(0,0, 150, 150)];
        _circleView.hidden = YES;
       _circleView.center = self.view.center;
    }
    return _circleView;
}

- (void)setupBottomView{
    CGFloat bottomHeight = bottomViewHeight ;
    
    CGFloat bottomY = CGRectGetMaxY(self.collectionView.frame);
 
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  bottomY, self.view.frame.size.width, bottomHeight)];
    bottomView.backgroundColor = UIColorFromRGB(0xf5f5f5);
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,  self.view.frame.size.width, 0.5)];
    lineView.backgroundColor = project_line_gray;
    [bottomView addSubview:lineView];
    UIButton * sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if (self.isFromHome) {
        if (self.isExists) {
            [sureBtn setTitle:@"去布置" forState:UIControlStateNormal];
            [sureBtn addTarget:self action:@selector(gotoReleaseHomework) forControlEvents:UIControlEventTouchUpInside];
        }else{
                [sureBtn setTitle:@"加入书架" forState:UIControlStateNormal];
                [sureBtn addTarget:self action:@selector(requestAddBookcase) forControlEvents:UIControlEventTouchUpInside];
        }
    }else{
        
            [sureBtn setTitle:@"加入书架" forState:UIControlStateNormal];
            [sureBtn addTarget:self action:@selector(requestAddBookcase) forControlEvents:UIControlEventTouchUpInside];
    }

    sureBtn.frame = CGRectMake(10, 5, bottomView.frame.size.width - 10*2, bottomHeight-5*2);
    sureBtn.layer.masksToBounds = YES;
    sureBtn.layer.cornerRadius = sureBtn.frame.size.height/2;
    sureBtn.backgroundColor = project_main_blue;

  
    [bottomView addSubview:sureBtn];
    bottomView.tag =  kSureBgBtnTag;
    [self.view addSubview:bottomView];
}

- (void)registerCell{
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookPreviewDirectoryCell class]) bundle:nil] forCellWithReuseIdentifier:BookPreviewDirectoryCellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookPreviewDirectoryCell class]) bundle:nil] forCellWithReuseIdentifier:BookPreviewDirectoryTwoCellIdentifier];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookPreviewDetailTypeCell class]) bundle:nil] forCellWithReuseIdentifier:BookPreviewDetailTypeCellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookPreviewDetailTitleCell class]) bundle:nil] forCellWithReuseIdentifier:BookPreviewDetailTitleCellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookPreviewDirectoryHeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:BookPreviewDirectoryHeaderViewIdentifier];
    
    [self.collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" ];
    [self.collectionView registerClass:[UICollectionReusableView class]  forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindheader" ];
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CartoonProfilePreviewCell class]) bundle:nil] forCellWithReuseIdentifier:CartoonProfilePreviewCellIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CartoonPreviewDirectoryPlayCell  class]) bundle:nil] forCellWithReuseIdentifier:CartoonPreviewDirectoryPlayCellIdentifier];
}

- (CGRect)getCollectionViewFrame{
    
    CGFloat bottomHeight = 0;
    
    if ( !self.isExists || self.isFromHome  ) {
        bottomHeight = bottomViewHeight ;
    }
     CGRect  collectionFrame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - bottomHeight);
    return collectionFrame;
}
#pragma mark ---
- (void)requestQueryBook{

    NSDictionary *parameterDic =nil;
    if (self.bookId &&self.bookType) {
        parameterDic  = @{@"bookId":self.bookId,@"getUnit":@"true",@"bookType":self.bookType};
    }
    [self sendHeaderRequest:[NetRequestAPIManager getRequestURLStr:NetRequestType_QueryBookById] parameterDic:parameterDic requestMethodType:RequestMethodType_POST requestTag:NetRequestType_QueryBookById];
}
- (void)requestAddBookcase{
    
    NSDictionary *parameterDic =nil;
    if (self.bookId &&self.bookType) {
        parameterDic  = @{@"bookId":self.bookId,@"getUnit":@"true",@"bookType":self.bookType};
    }
    [self sendHeaderRequest:[NetRequestAPIManager getRequestURLStr:NetRequestType_TeacherAddBookToBookShelf] parameterDic:parameterDic requestMethodType:RequestMethodType_POST requestTag:NetRequestType_TeacherAddBookToBookShelf];
    
}
- (void)requestQueryCartoonPages:(NSString *)bookId{
    
    [self sendHeaderRequest:[NetRequestAPIManager getRequestURLStr:NetRequestType_QueryCartoonPages] parameterDic:@{@"bookId":bookId} requestMethodType:RequestMethodType_POST requestTag:NetRequestType_QueryCartoonPages];
}
- (void)setNetworkRequestStatusBlocks{

    WEAKSELF
    [self setNetSuccessBlock:^(NetRequest *request, id successInfoObj) {
        STRONGSELF
        if (request.tag == NetRequestType_QueryBookById) {
            strongSelf.detailModel = [[BookPreviewModel alloc]initWithDictionary:successInfoObj error:nil];
            [strongSelf updateCollectionView];
            if ([self.detailModel.book.bookType isEqualToString:@"Book"]||[self.detailModel.book.bookType isEqualToString:@"Cartoon"]) {
                if (strongSelf.isFromHome) {
                     [strongSelf setupBottomView];
                }else{
                    if ( !strongSelf.isExists ) {
                        [strongSelf setupBottomView];
                    }
                    
                }
            }else if ([strongSelf.detailModel.book.bookType isEqualToString:@"JFBook"]){
                if (strongSelf.isFromHome) {
                    [strongSelf setupBottomView];
                }else{
                    if (!strongSelf.isExists) {
                        [strongSelf setupBottomView];
                    }
                }
            }
           
        }else if(request.tag == NetRequestType_TeacherAddBookToBookShelf){
            strongSelf.isExists =  YES;
            [strongSelf showAlert:TNOperationState_OK content:@"书本添加成功" block:^(NSInteger index) {
                [strongSelf gotoBookcaseVC];
            }];
            NSLog(@"加入成功");
        }else if (request.tag == NetRequestType_QueryCartoonPages) {
            NSArray * pagesArray = successInfoObj[@"pages"];
           
            [strongSelf.cartoonBookDownloadUrlArray  removeAllObjects];
            [strongSelf.playCartoonBookArray removeAllObjects];
            [strongSelf.cartoonBookImgArray removeAllObjects];
            [strongSelf screeningCartoon:pagesArray];
         
        }
 
    }];
}
- (void)backViewController{
    
    if (self.isExists && self.selectedBlock) {
        self.selectedBlock(self.indexPath);
    }
    [super backViewController];
}
- (void)gotoBookcaseVC{
 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATE_BOOKCASE" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATE_HOME_BOOKCASE_LIST" object:nil];
       UIViewController * BookcaseVC = self.navigationController.viewControllers[2];
    if ([BookcaseVC isKindOfClass:[BookcaseViewController class]]) {
        
        [self.navigationController popToViewController:BookcaseVC  animated:YES];
    }else{
      
       UIView * bgView = [self.view viewWithTag:kSureBgBtnTag];
        for (UIView * view in bgView.subviews) {
            if ([view isKindOfClass:[UIButton class]]) {
                UIButton * btn = (UIButton * )view;
                [btn setTitle:@"去布置" forState:UIControlStateNormal];
                [btn removeTarget:self action:@selector(requestAddBookcase) forControlEvents:UIControlEventTouchUpInside];
                [btn addTarget:self action:@selector(gotoReleaseHomework) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        self.isExists = YES;
    }

}
- (void)screeningCartoon:(NSArray *)pagesArray{
    
    if (pagesArray.count > 0) {
        for (int i = 0; i <[pagesArray  count]; i++) {
            NSDictionary *pageDic = pagesArray[i];
            NSArray * sentences = pageDic[@"sentences"];
            for (int j = 0; j< [sentences count]; j++) {
                NSDictionary * sectenceDic = sentences[j];
                NSString * audioUrl = sectenceDic[@"voice"];
                //翻译
                NSString * cn = sectenceDic[@"cn"];
                //原文
                NSString * en = sectenceDic[@"en"];
                //url 音频播放地址  page 当前页   number 当前页的第几局
                NSDictionary * dic =  @{@"page":@(i+1),@"nubmer":@(j+1),@"url":audioUrl,@"cn":cn,@"en":en};
                [self.cartoonBookDownloadUrlArray addObject:dic];
                
            }
            [self.cartoonBookImgArray addObject:pageDic[@"image"]];
            if (!sentences ||(sentences && sentences== 0)) {
                NSString * content = [NSString stringWithFormat:@"第%zd页,音频资源下载失败",i+1];
                [self showAlert:TNOperationState_Fail content:content];
                return ;
            }
            
        }
    }
    
    if ([self.cartoonBookDownloadUrlArray count]>0) {
        
        self.currentDownPage = 0;
        NSString *urlSr = self.cartoonBookDownloadUrlArray.firstObject[@"url"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.circleView.progress = 0;
            self.circleView.hidden = NO;
            self.mongoliaView.hidden = NO;
        });
        [self downLoadAudio:urlSr];
    }
    
}
#pragma mark ---

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    NSInteger section = 0;
    if (!self.detailModel.book) {
        section = 0;
    }else{
        
        if ([self.detailModel.book.bookType isEqualToString:@"Book"]) {
             section = 2 + [self.detailModel.book.bookUnits count];
        }else if ([self.detailModel.book.bookType  isEqualToString:@"Cartoon"]){
             section = 4;
        }else if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]){
            
            section = 1 + [self.detailModel.book.bookUnits count];
        }

    }
    return section;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger   rows = 0;
    if (section == 0) {
        rows = 1;
    }else if (section == 1){
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            BookUnitModel * model = self.detailModel.book.bookUnits[section -1];
            if (model.children) {
                rows = [model.children count]+1;
            }else{
                rows = 1;
            }
        } else{
            rows = [self.detailModel.book.practiceTypes count];
            
        }
    }else {
    
        if ([self.detailModel.book.bookType isEqualToString:@"Book"]) {
            BookUnitModel * model = self.detailModel.book.bookUnits[section -2];
            rows = [model.children count]+1;
        }else if ([self.detailModel.book.bookType  isEqualToString:@"Cartoon"]){
            rows = 1;
        }else if ([self.detailModel.book.bookType  isEqualToString:@"JFBook"]){
           
            BookUnitModel * model = self.detailModel.book.bookUnits[section -1];
            if (model.children) {
                 rows = [model.children count]+1;
            }else{
                rows = 1;
            }
            
        }
        
    }
    return rows;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = nil;
    if (indexPath.section == 0) {
    
        BookPreviewDetailTitleCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDetailTitleCellIdentifier forIndexPath:indexPath];
        [tempCell setupPreviewDetailInfo:self.detailModel.book];
        cell = tempCell;
    }
    
    else if (indexPath.section == 1)
    {
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            cell = [self  confightJFDirectoryCell:collectionView withIndexPath:indexPath];
        } else{
            cell = [self confightPreviewTypeCell:collectionView withIndexPath:indexPath];
        }
    }else if (indexPath.section >= 2){
        
        if ([self.detailModel.book.bookType isEqualToString:@"Book"]) {
            cell = [self confightBookDirectoryCell:collectionView withIndexPath:indexPath];
            
        }else if ([self.detailModel.book.bookType  isEqualToString:@"Cartoon"]){
            cell = [self  confightCartoonDirectoryCell:collectionView withIndexPath:indexPath];
           
        }else   if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
         
            cell = [self  confightJFDirectoryCell:collectionView withIndexPath:indexPath];
        }
    }
 
    return cell;
}
//书本 绘本 分类
- (UICollectionViewCell *)confightPreviewTypeCell:(UICollectionView *)collectionView withIndexPath:(NSIndexPath *)indexPath{
       UICollectionViewCell * cell = nil;
    BookPreviewDetailTypeCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDetailTypeCellIdentifier forIndexPath:indexPath];
    [tempCell setupDetailType:self.detailModel.book.practiceTypes[indexPath.item] withImgDic: self.unityIconDic];
    cell = tempCell;
    return cell;
}
//绘本描述
- (UICollectionViewCell *)confightCartoonDirectoryCell:(UICollectionView *)collectionView withIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell = nil;
    if (indexPath.section == 2) {
        CartoonProfilePreviewCell * tempCell =  [collectionView dequeueReusableCellWithReuseIdentifier:CartoonProfilePreviewCellIdentifier forIndexPath:indexPath];
        [tempCell setupDetailName:self.detailModel.book.intro];
        cell = tempCell;
    }else{
        CartoonPreviewDirectoryPlayCell * tempCell =  [collectionView dequeueReusableCellWithReuseIdentifier:CartoonPreviewDirectoryPlayCellIdentifier forIndexPath:indexPath];
        [tempCell setupImageUrl:self.detailModel.book.coverImage];
        cell = tempCell;
    }
    return cell;
}
//书本目录

- (UICollectionViewCell *)confightBookDirectoryCell:(UICollectionView *)collectionView withIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell = nil;
    BookUnitModel * model = self.detailModel.book.bookUnits[indexPath.section -2];
    if (indexPath.row == 0) {
        BookPreviewDirectoryCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDirectoryCellIdentifier forIndexPath:indexPath];
        [tempCell setupDirectoryInfo:model];
        cell = tempCell;
    }else {
        
        BookPreviewDirectoryCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDirectoryTwoCellIdentifier forIndexPath:indexPath];
        BookUnitModel *children = model.children[indexPath.row -1];
        [tempCell setupChildrenDirectoryInfo: children];
        cell = tempCell;
    }
    return cell;
}
//教辅目录
- (UICollectionViewCell *)confightJFDirectoryCell:(UICollectionView *)collectionView withIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell = nil;
    BookUnitModel * model = self.detailModel.book.bookUnits[indexPath.section -1];
    if (indexPath.row == 0) {
        BookPreviewDirectoryCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDirectoryCellIdentifier forIndexPath:indexPath];
        [tempCell setupDirectoryInfo:model];
        cell = tempCell;
    }else {
        
        BookPreviewDirectoryCell * tempCell = [collectionView dequeueReusableCellWithReuseIdentifier:BookPreviewDirectoryTwoCellIdentifier forIndexPath:indexPath];
        BookUnitModel *children = model.children[indexPath.row -1];
        [tempCell setupChildrenDirectoryInfo: children];
        cell = tempCell;
    }
    return cell;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize itemSize =  CGSizeZero;
    if (indexPath.section == 0) {
        itemSize = CGSizeMake(IPHONE_WIDTH, FITSCALE(120));
    }else if(indexPath.section == 1){
        
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            itemSize = CGSizeMake(IPHONE_WIDTH, FITSCALE(30));
        }else{
            if ([self.detailModel.book.practiceTypes count] == 1) {
                 itemSize = CGSizeMake(IPHONE_WIDTH, FITSCALE(60));
            }else
              itemSize = CGSizeMake(IPHONE_WIDTH/2, FITSCALE(60));
        }
    }else if(indexPath.section >= 2){
        
        if ([self.detailModel.book.bookType isEqualToString:@"Book"]) {
              itemSize = CGSizeMake(IPHONE_WIDTH, FITSCALE(30));
        }else if ([self.detailModel.book.bookType  isEqualToString:@"Cartoon"]){
            if (indexPath.section == 2) {
                 CGFloat infoTextHeight = [ProUtils heightForString:self.detailModel.book.intro andWidth:IPHONE_WIDTH-20];
                 itemSize = CGSizeMake(IPHONE_WIDTH, infoTextHeight + FITSCALE(50+10));
            }else{
                itemSize = CGSizeMake(IPHONE_WIDTH, IPHONE_WIDTH);
            }
        }else  if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            itemSize = CGSizeMake(IPHONE_WIDTH, FITSCALE(30));
        }
    }
    return itemSize;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets edgeInsets = UIEdgeInsetsZero;

    return edgeInsets;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    CGFloat  spacing = 0.0f;
   
    return spacing;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    CGFloat  spacing = 0.0f;
   
    return spacing;
}


- (UICollectionReusableView *) confightDefultFooterView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind withIndexPath:(NSIndexPath *)indexPath{
    NSString * reuseIdentifier = @"UICollectionElementKindSectionFooter";
    if (kind == UICollectionElementKindSectionFooter) {
        reuseIdentifier = @"UICollectionElementKindSectionFooter";
    }else if (kind == UICollectionElementKindSectionHeader){
        reuseIdentifier = @"UICollectionElementKindheader";
        
    }
    UICollectionReusableView * reusableView  = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
 
    return reusableView;
    
}

//目录 标题
- (UICollectionReusableView *) confightDirectoryTitleHeaderView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind withIndexPath:(NSIndexPath *)indexPath withReuseIdentifier:(NSString *)reuseIdentifier{
    BookPreviewDirectoryHeaderView * sectionView  = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    return sectionView;
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *headerView = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
   
        headerView  = [self confightDefultFooterView:collectionView  viewForSupplementaryElementOfKind:kind withIndexPath:indexPath];
    }else if([kind isEqualToString:UICollectionElementKindSectionHeader]){
        if ([self.detailModel.book.bookType isEqualToString:@"Book"] && indexPath.section == 2){
            
            headerView  = [self  confightDirectoryTitleHeaderView:collectionView viewForSupplementaryElementOfKind:kind withIndexPath:indexPath withReuseIdentifier:BookPreviewDirectoryHeaderViewIdentifier];
            
        }else if ([self.detailModel.book.bookType isEqualToString:@"JFBook"] && indexPath.section == 1){
         
           headerView  =  [self  confightDirectoryTitleHeaderView:collectionView viewForSupplementaryElementOfKind:kind withIndexPath:indexPath withReuseIdentifier:BookPreviewDirectoryHeaderViewIdentifier];
           
        } else{
            headerView  = [self confightDefultFooterView:collectionView  viewForSupplementaryElementOfKind:kind withIndexPath:indexPath];
        }
        
    }
  
    return headerView;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize itemSize = CGSizeZero;
    if (section == 2 && [self.detailModel.book.bookUnits count] >0) {
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            itemSize = CGSizeZero;
        } else{
            itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(44)};
            
        }
    }else if (section == 0){
         itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(6)};
    }else if (section == 1 ){
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]){
             itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(44)};
        }else{
            itemSize = CGSizeZero;
            
        }
    }
    return itemSize;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
     CGSize itemSize = CGSizeZero;
    if (section == 0 ){
        itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(6)};
    } else if (section == 1 ){
        if ([self.detailModel.book.bookType isEqualToString:@"JFBook"]) {
            itemSize = CGSizeZero;
        }else{
            itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(6)};
        }
    }else if (section == 2 && [self.detailModel.book.bookType isEqualToString:@"Cartoon"]){
        itemSize = (CGSize){IPHONE_WIDTH,FITSCALE(6)};
    }
    return itemSize;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     if (indexPath.section == 3 &&[self.detailModel.book.bookType isEqualToString:@"Cartoon"]) {
        [self requestQueryCartoonPages:self.bookId];
        
    }
}


- (void)gotoReleaseHomework{
    
    if ([self.bookType isEqualToString:@"JFBook"]) {
        AssistantsHomeworkViewController * bookHomeworkVC = [[AssistantsHomeworkViewController alloc]initWithBookId:self.bookId  ];
        [self pushViewController:bookHomeworkVC];
    }else{
        BookHomeworkViewController * bookHomeworkVC = [[BookHomeworkViewController alloc]initWithBookId:self.bookId withBookType:self.bookType];
        [self pushViewController:bookHomeworkVC];
    }
}

- (void)gotoPictureBookAudioVC{

    PreviewPictureBookAudioViewController * previewPBAVC = [[PreviewPictureBookAudioViewController alloc]initWithName:self.detailModel.book.name withData:self.playCartoonBookArray];
    [self pushViewController:previewPBAVC];
}
 


#pragma mark ---
- (void)downLoadAudio:(NSString *)audioURLStr{
    
    WEAKSELF
    //    strongSelf.downIndex ++;
    [[HSDownloadManager sharedInstance] download:audioURLStr progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    } state:^(DownloadState state,NSString *url) {
        STRONGSELF
        if (state == DownloadStateCompleted) {
            
            for (int i = 0; i< [strongSelf.cartoonBookDownloadUrlArray count]; i++) {
                NSDictionary * dic = strongSelf.cartoonBookDownloadUrlArray[i];
                if ([url isEqualToString:dic[@"url"]]) {
                    [strongSelf setupDownloadIndex: i+1 withDownFilePath:[[HSDownloadManager sharedInstance] getFileAudioPath:url]];
                    if (i == [strongSelf.cartoonBookDownloadUrlArray count]-1) {
                    
                        dispatch_async(dispatch_get_main_queue(), ^{
 
                            [strongSelf gotoPictureBookAudioVC];
                            strongSelf.circleView.progress = 1.00;
                            strongSelf.circleView.hidden = YES;
                            self.mongoliaView.hidden = YES;
                        });
                        
                    }else{
                       
                        float download = (float)(i+1)/(float)[strongSelf.cartoonBookDownloadUrlArray count];
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            strongSelf.circleView.progress = download;
                            strongSelf.circleView.hidden = NO;
                            self.mongoliaView.hidden = NO;
                        });
                         
                        [strongSelf downLoadAudio:strongSelf.cartoonBookDownloadUrlArray[i+1][@"url"]];
                        
                    }
                }
                
            }
        }
        
        
    }];
    
    
}

- (void)setupDownloadIndex:(NSInteger )downloadIndex withDownFilePath:(NSString *)filePath{
    
    WEAKSELF
    STRONGSELF
    if (downloadIndex -1 == 0) {
        strongSelf.currentDownPage ++;
        NSDictionary * currentDic= strongSelf.cartoonBookDownloadUrlArray[downloadIndex -1];
        NSMutableDictionary * tempDic =  [[NSMutableDictionary alloc]initWithDictionary:currentDic];
        //修改为本地播放地址
        [tempDic setObject:filePath forKey:@"url"];
 
        NSMutableArray * tempArray =  [[NSMutableArray alloc]initWithObjects:tempDic, nil];
        NSDictionary * pageDic = @{@"image":strongSelf.cartoonBookImgArray[downloadIndex -1],@"section":tempArray};
        [strongSelf.playCartoonBookArray addObject: pageDic];
        
    }else{
        //
        NSDictionary * currentDic = strongSelf.cartoonBookDownloadUrlArray[downloadIndex -1];
        //前一条
        NSDictionary * preDic= strongSelf.cartoonBookDownloadUrlArray[downloadIndex -2];
        NSMutableDictionary * tempDic =  [[NSMutableDictionary alloc]initWithDictionary:currentDic];
        //修改为本地播放地址
        [tempDic setObject:filePath forKey:@"url"];
        //在同一页
        if ( [currentDic[@"page"] integerValue] == [preDic[@"page"] integerValue]) {
            
            NSMutableDictionary * pageDic  = [NSMutableDictionary dictionary];
            
             [pageDic addEntriesFromDictionary: strongSelf.playCartoonBookArray[[currentDic[@"page"] integerValue]-1]];

            NSMutableArray *currentPageArray =[[NSMutableArray alloc]initWithArray: pageDic[@"section"]];
            [currentPageArray addObject:tempDic];
            [pageDic setObject:currentPageArray forKey:@"section"];
             NSInteger index = [currentDic[@"page"] integerValue]-1;
            [strongSelf.playCartoonBookArray replaceObjectAtIndex:index  withObject:pageDic];
            
        }else{
            strongSelf.currentDownPage ++;
            NSMutableArray *currentPageArray = [NSMutableArray array];
            [currentPageArray addObject:tempDic];

            NSDictionary * pageDic = @{@"image":strongSelf.cartoonBookImgArray[strongSelf.currentDownPage -1],@"section":currentPageArray};
            [strongSelf.playCartoonBookArray addObject: pageDic];
           
        }
        
    }
    
    //下载完成后 进行下一个任务
    if ( downloadIndex < strongSelf.cartoonBookDownloadUrlArray.count) {
 
       
    }else{
        
    }
    
}
- (NSMutableArray *)playCartoonBookArray{
    
    if (!_playCartoonBookArray) {
        _playCartoonBookArray = [[NSMutableArray alloc]init];
    }
    return _playCartoonBookArray;
}

- (NSMutableArray *)cartoonBookImgArray{
    if (!_cartoonBookImgArray) {
        _cartoonBookImgArray = [[NSMutableArray alloc]init];
    }
    return _cartoonBookImgArray;
}
- (NSMutableArray *)cartoonBookDownloadUrlArray{
    
    if (!_cartoonBookDownloadUrlArray ) {
        _cartoonBookDownloadUrlArray = [[NSMutableArray alloc]init];
    }
    return _cartoonBookDownloadUrlArray;
}
@end
